package com.jnu.student;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.jnu.student.data.AchievementDataStorage;
import com.jnu.student.data.achievementPointDataBank;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class statisticsFragment extends Fragment {
    public statisticsFragment() {
        // Required empty public constructor
    }
    public static statisticsFragment newInstance() {
        statisticsFragment fragment = new statisticsFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    private TextView textAchievementData;
    private LineChart chart;
    private AchievementDataStorage achievementDataStorage;
    private SharedPreferences sharedPreferences;

    private double totalScore;
    private Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
        achievementDataStorage = new AchievementDataStorage();
        sharedPreferences = getActivity().getSharedPreferences("statisticPrefs", Context.MODE_PRIVATE);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_statistics, container, false);
        // 获取TextView的引用
        textAchievementData = rootView.findViewById(R.id.text_achievement_data);
        // 获取折线图控件引用
        chart = rootView.findViewById(R.id.chart);

        List<Double> past15DaysPoints = new AchievementDataStorage().loadAchievementData(requireContext());
        // 设置 x 轴和 y 轴的数据
        ArrayList<Entry> values = new ArrayList<>();
        for (int i = 0; i < past15DaysPoints.size(); i++) {
            values.add(new Entry(i, past15DaysPoints.get(i).floatValue()));
        }

        LineDataSet dataSet = new LineDataSet(values, "过去15天的数据");

        LineData lineData = new LineData(dataSet);
        chart.setData(lineData);
        chart.invalidate(); // 刷新图表

        return rootView;
    }


    @Override
    public void onResume() {
        super.onResume();
        if (shouldRefreshData()) {
            updateLineChartData();
            saveLastRefreshDate();
        }
        startTextViewUpdate();  // 继续更新TextView内容
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacksAndMessages(null);  // 在 onPause 中移除定时任务
        stopTextViewUpdate();  // 停止更新TextView内容
    }

    private void startTextViewUpdate() {
        mHandler.post(mUpdateTimeTask);
    }

    private void stopTextViewUpdate() {
        mHandler.removeCallbacks(mUpdateTimeTask);
    }

    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            // 在此处更新TextView内容
            totalScore = new achievementPointDataBank().loadAchievementPoints(requireActivity());
            textAchievementData.setText(String.valueOf(totalScore));

            // 在此处设置更新的时间间隔（毫秒），例如1000表示1秒钟
            mHandler.postDelayed(this, 1000);
        }
    };

    private void updateLineChartData() {
        // 在此处更新折线图的数据
        // 例如，设置折线图的数据源、刷新界面等操作
        // 读取当天的数据
        double todayPoints = new achievementPointDataBank().loadAchievementPoints(requireContext());
        // 更新当天的数据
        achievementDataStorage.updateAchievementData(requireContext(), todayPoints);
        //读取更新后的数据
        List<Double> past15DaysPoints = new AchievementDataStorage().loadAchievementData(requireContext());
        // 设置 x 轴和 y 轴的数据
        ArrayList<Entry> values = new ArrayList<>();
        for (int i = 0; i < past15DaysPoints.size(); i++) {
            values.add(new Entry(i, past15DaysPoints.get(i).floatValue()));
        }

        LineDataSet dataSet = new LineDataSet(values, "过去15天的数据");

        LineData lineData = new LineData(dataSet);
        chart.setData(lineData);
        chart.invalidate(); // 刷新图表
    }

    private boolean isSameDay(Calendar cal1, Calendar cal2) {
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
                cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
    }
    private boolean shouldRefreshData() {
        long lastRefreshTime = sharedPreferences.getLong("lastRefreshTime", 0);
        Calendar lastRefreshDate = Calendar.getInstance();
        lastRefreshDate.setTimeInMillis(lastRefreshTime);

        Calendar currentDate = Calendar.getInstance();

        return !isSameDay(lastRefreshDate, currentDate);
    }

    private void saveLastRefreshDate() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putLong("lastRefreshTime", System.currentTimeMillis());
        editor.apply();
    }
}